package com.zjx.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.zjx.dto.UserLoginRespDto;
import com.zjx.dto.req.UserLoginReqDto;
import com.zjx.dto.req.UserRegisterReqDto;
import com.zjx.dto.UserRegisterRespDto;
import com.zjx.dto.VerifyCodeRespDto;
/*import com.zjx.po.UserInfo;*/
import com.zjx.mapper.UserInfoMapper;
import com.zjx.po.UserInfo;
import com.zjx.service.IUserInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zjx.util.CaptchaUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.util.Pair;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.HashMap;

/**
 * <p>
 * 用户信息 服务实现类
 * </p>
 *
 * @author huli
 * @since 2024-02-01
 */

@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements IUserInfoService {

    static HashMap<String, String> map = new HashMap<>();

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Override
    public VerifyCodeRespDto imgVerifyCode() {
        Pair<String, String> pair = CaptchaUtils.getImageBase64();
        String sessionId = IdWorker.get32UUID();
        // 存储起来 下一次发送注册请求时 进行验证
        //  可以把sessionId和图片验证码的对应关系存储起来
        map.put(sessionId, pair.getFirst());
        VerifyCodeRespDto verifyCodeRespDto = VerifyCodeRespDto.builder()
                .sessionId(sessionId)
                .img(pair.getSecond())
                .build();
        return verifyCodeRespDto;
    }

    @Override
    public UserRegisterRespDto register(UserRegisterReqDto reqDto) {
        UserRegisterRespDto respDto = UserRegisterRespDto.builder().build();
        // 要验证两个条件
        // 1、验证码是否正确
        // 2、用户名是否使用过
        String sessionId = reqDto.getSessionId();
        // 传进来的用户填写的验证码 和 实际生成的验证码 是否匹配
        if (!reqDto.getVelCode().equals(map.get(sessionId))) {
            respDto.setType(1);
            return respDto;
        }
        // select count(*) from user_info where username = '13654561111'
        LambdaQueryWrapper<UserInfo> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(UserInfo::getUsername, reqDto.getUsername());
        Long count = userInfoMapper.selectCount(lambdaQueryWrapper);
        if (count == 1) {
            respDto.setType(2);
            return respDto;
        }

        // 密码往往是通过md5进行加密存储
        // DigestUtils是spring提供的工具类 需要的参数是字节数组
        // INSERT INTO `user_info` (`id`, `username`, `password`, `salt`, `nick_name`, `user_photo`, `user_sex`, `account_balance`, `status`, `create_time`, `update_time`)
        // VALUES
        //	(2, '13654562222', 'e10adc3949ba59abbe56e057f20f883e', '0', '13654562222', NULL, NULL, 0, 0, '2024-01-04 18:03:39', '2024-01-04 18:03:39');
        byte[] bytes = reqDto.getPassword().getBytes(StandardCharsets.UTF_8);
        UserInfo userInfo = UserInfo.builder()
                .username(reqDto.getUsername())
                .password(DigestUtils.md5DigestAsHex(bytes))
                .nickName(reqDto.getUsername())
                .salt("0")
                .accountBalance(0L)
                .status((byte) 0)
                .createTime(LocalDateTime.now())
                .updateTime(LocalDateTime.now())
                .build();
        userInfoMapper.insert(userInfo);

        respDto.setType(0);
        respDto.setUid(userInfo.getId());
        respDto.setToken(userInfo.getId().toString());
        return respDto;
    }

    @Override
    public UserLoginRespDto login(UserLoginReqDto reqDto) {
        //用户名或密码错误
        String password = DigestUtils.md5DigestAsHex(reqDto.getPassword().getBytes(StandardCharsets.UTF_8));
        LambdaQueryWrapper<UserInfo> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(UserInfo::getUsername, reqDto.getUsername()).eq(UserInfo::getPassword, password);
        UserInfo userInfo = userInfoMapper.selectOne(lambdaQueryWrapper);

        if (userInfo != null) {
            return UserLoginRespDto.builder()
                    .type(0)
                    .uid(userInfo.getId())
                    .nickName(userInfo.getNickName())
                    .token("token_" + userInfo.getId())
                    .build();
        }

        LambdaQueryWrapper<UserInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserInfo::getUsername, reqDto.getUsername());
        Long count = userInfoMapper.selectCount(queryWrapper);

        if (count == 0) {
            //用户名不存在
            return UserLoginRespDto.builder().type(1).build();

        }
        //用户名存在
        //密码错误
        return UserLoginRespDto.builder().type(2).build();
    }
}
